//
//  HS_DetailCollectionViewCell.m
//  悦享
//
//  Created by 韩双 on 16/3/17.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "HS_DetailCollectionViewCell.h"
#import <UIImageView+WebCache.h>

@interface HS_DetailCollectionViewCell ()

@property (nonatomic, retain) UISlider *slider;   /**< 视频进度条 */
@property (nonatomic, strong) AVPlayerItem *playerItem; /**< 播放项目 */
@property (nonatomic, retain) UIImageView *imageView;  /**< 动态图和图片 */
@property (nonatomic, retain) NSString *mv_url;    /**< 播放网址 */
@property (nonatomic, retain) UILabel *timeStartLable;   /**< 视频开始播放时间 */
@property (nonatomic, retain) UILabel *timeEndLable;  /**< 视频总时长 */
@property (nonatomic, assign) CGFloat totaDuration;   /**< 视频时长 */
@property (nonatomic, assign) BOOL isUpData;

@end


@implementation HS_DetailCollectionViewCell

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.imageView = [[UIImageView alloc] init];
        [self.contentView addSubview:_imageView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerAction:) name:@"playerPause" object:nil];
        
    }
    return self;

    
}

- (void)setModel:(HS_detailModle *)model {
    
    [_playView removeFromSuperview];
    [_startButton removeFromSuperview];
    
    _model = model;
    
    if (_model.video_url) {
        self.playView = [[UIView alloc] init];
        [self.contentView addSubview:_playView];
        _imageView.alpha = 0;
        _playView.alpha = 1;
        _playView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        // 添加播放器
        self.mv_url = _model.video_url;
        
        self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playView addSubview:_startButton];
        
        self.endView = [[UIView alloc] initWithFrame:CGRectMake(0, _playView.frame.size.height - 50, _playView.frame.size.width, 50)];
        [_playView addSubview:_endView];
    }
    
    if (_model.mp4_url) {
        _imageView.alpha = 1;
       _imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [_imageView sd_setImageWithURL:[NSURL URLWithString:_model.mp4_url] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];

    }
    
    
    _startButton.frame = CGRectMake(0, 0, 50, 50);
    _startButton.center = _playView.center;
    [_startButton setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];

    _endView.backgroundColor = [UIColor clearColor];
    
    // 全屏开关
    self.fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _fullButton.frame = CGRectMake(_endView.frame.size.width - 40, 15, 20, 20);
    [_fullButton setImage:[UIImage imageNamed:@"iconfont-quanping"] forState:UIControlStateNormal];
    [_endView addSubview:_fullButton];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(80, 0, self.endView.frame.size.width - 180, 50)];
    
    // 改变条的颜色 滑动后左边条的颜色
    _slider.minimumTrackTintColor = [UIColor redColor];
    // 右边的颜色
    _slider.maximumTrackTintColor = [UIColor whiteColor];
    
    // 添加方法
    [_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    [_slider setThumbImage:[UIImage imageNamed:@"iconfont-yuan"] forState:UIControlStateNormal];
    
    [_endView addSubview:_slider];
    
    self.timeStartLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, 50, 20)];
    _timeStartLable.textColor = [UIColor whiteColor];
    _timeStartLable.font = [UIFont systemFontOfSize:13];
    [_endView addSubview:_timeStartLable];
    
    self.timeEndLable = [[UILabel alloc] initWithFrame:CGRectMake(self.endView.frame.size.width - 80, 15, 50, 20)];
    _timeEndLable.font = [UIFont systemFontOfSize:13];
    _timeEndLable.textColor = [UIColor whiteColor];
    [_endView addSubview:_timeEndLable];
    
    [self addAVPlayer];
    
    // 添加进度监听
    [self addProgressObserver];
    
    
    
    // 赋初值，提升用户体验
    self.slider.value = 0;
    self.timeStartLable.text = @"--:--";
    self.timeEndLable.text = @"--:--";

}

#pragma mark - 全屏点击方法
- (void)fullAction:(UIButton *)button {
    
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        // 竖屏
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        
    }else{
        // 横屏
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        
    }
    
    // 获取到当前屏幕旋转的方向
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    NSLog(@"向左横屏");
    [self setPlayFrame];
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
    }

}

- (void)playerAction:(NSNotificationCenter *)n {
    
    [self.player pause];
    
}

#pragma mark - slider控制播放

- (void)sliderAction:(UISlider *)slider {
    
    NSLog(@"%0.2f", slider.value);
    
    // 获取到当前进度时间
    CGFloat currentTime = self.totaDuration * slider.value;
    // 转化为CMTime
    CMTime draTime = CMTimeMake(currentTime, 1);
    
    [self.player seekToTime:draTime completionHandler:^(BOOL finished) {
        
        // 到了时间之后 开始播放
        [self.player play];
    }];
    
    
}
- (void)setPlayFrame {
    
    self.playerLayer.frame = CGRectMake(5, 5, SREEN_WIDTH - 10, self.playView.frame.size.height - 10);

}
/** 播放进度监听*/
- (void)addProgressObserver {
    
    // CMTime 是专门计算视频的时间格式
    // Core Media
    // 参数1：设置监听的时间间隔
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 监听干什么
        // 获取到总的视频时间
        CGFloat duration = [_model.duration floatValue];
        
        // 获取到当前时间
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        // 把总时间转化为字符串显示在lable上
        NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int)duration % 60];
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];

        self.timeStartLable.text = currentT;
        self.timeEndLable.text = durationT;
        
        // 记录总时间，slider需要使用
        self.totaDuration = duration;
        
        // slider的value
        self.slider.value = current / duration;
        
        
        
        
    }];
}


/** 添加播放器 */
- (void)addAVPlayer {
    [_playerLayer removeFromSuperlayer];
    [[HS_importManager shareManager] pause];

    self.player = [[AVPlayer alloc] init];
    AVPlayerLayer *playerLayer = [[AVPlayerLayer alloc] init];
    
    NSString *video_url = _model.video_url;
    video_url = [video_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    // 创建播放项目对象
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:video_url]];
    // 创建承载播放器的layer
    [_player replaceCurrentItemWithPlayerItem:playerItem];
    
    // 设置视频填充模式
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    // 创建承载播放器的layer
    playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    playerLayer.frame = _playView.frame;
    // 将播放器放到playView上
    [self.playView.layer insertSublayer:playerLayer atIndex:0];
    
    // 添加轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_playView addGestureRecognizer:tap];
    
}

// 轻拍
- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (_isUpData) {
        [UIView animateWithDuration:0.5 animations:^{
            
            _startButton.alpha = 0;
            _endView.alpha = 0;
            
        }];
    } else {
        _startButton.alpha = 1;
        _endView.alpha = 1;
    }
    _isUpData = !_isUpData;
    
}
    

@end
